import {currentAccount, loginWxampForWechatCallback} from "../service/api/api-login";
import access from "./access";

export const formatTime = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return (
        [year, month, day].map(formatNumber).join('/') +
        ' ' +
        [hour, minute, second].map(formatNumber).join(':')
    )
}

const formatNumber = (n: number) => {
    const s = n.toString()
    return s[1] ? s : '0' + s
}

export const handleCode = (res: Object, msg = '') => {
    wx.showToast({
        title: res?.code === 0 ? msg : (res?.msg || '失败'),
        icon: res?.code === 0 ? 'success' : 'error',
        duration: 1500
    })
}

export const handleErrCode = (msg = '失败', icon = 'none') => {
    wx.showToast({
        title: msg,
        icon: icon,
        duration: 1500
    })
}

/**
 * 创建分享信息朋友
 * @param task 任务
 * @param currentUser 当前用户
 * @param wxCodes 之前分享的用户列表
 * @param path 目标页面地址
 * @param url 文章地址
 */
export const createShareAppMessageInfo = (task = {}, currentUser = {}, wxCodes = [], path = '', url = '') => {
    return {
        title: task.name ?? '',
        path: `${path}?&task=${encodeURIComponent(JSON.stringify(task))}&shareAccountId=${currentUser.id}&wxCodes=${JSON.stringify(wxCodes)}&url=${url}`,
        imageUrl: task.routeCoverUrl ?? '',
    }
}
/**
 * 创建分享信息朋友圈
 * @param task 任务
 * @param currentUser 当前用户
 * @param wxCodes 之前分享的用户列表
 * @param url 文章地址
 */
export const createShareTimelineInfo = (task = {}, currentUser = {}, wxCodes = [], url = '') => {
    return {
        title: task.name ?? '',
        query: `task=${encodeURIComponent(JSON.stringify(task))}&shareAccountId=${currentUser.id}&wxCodes=${JSON.stringify(wxCodes)}&url=${url}`,
        imageUrl: task.routeCoverUrl ?? '',
    }
}
/**
 * 微信登录处理
 * @param code 当前用户code
 * @param silent 是否静默登录，代表不需要跳转到首页
 * @param callBack 回调函数
 */
export const loginWxampForWechatFun = (code: String, silent?: Boolean, callBack?: Function) => {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //小程序使用微信登录
    loginWxampForWechatCallback({serviceName: "cqgxq", code}).then(response => {
        loginCallback(response, silent, callBack)
    })
}

export const loginCallback = (response, silent?: Boolean, callBack?: Function) => {
    let app = getApp();
    if (response.code === 0) {
        const {state, satoken} = response.data;
        app.globalData.currentUserState = state;
        /**
         * state 状态
         * 1、无账号
         * 2、有账号，未激活
         * 3、有账号、有激活、未启用
         * 4、有账号、有激活、已启用
         */

        if (state === 1) {
            //无账号
            //跳转到注册页面，注册用户，需要输入手机号、姓名、组织
            wx.reLaunch({
                url: '/pages/bind/index'
            })
        } else if (state === 2 || state === 3) {
            //有账号，未激活
            //有账号、有激活、未启用
            wx.reLaunch({
                url: `/pages/state/index?state=${state}`
            })

        } else if (state === 4) {
            //有账号、有激活、已启用
            //正常跳转到主界面
            app.globalData.satoken = satoken;
            currentAccount().then(responseCurrentUser => {
                if (responseCurrentUser.code == 0) {
                    app.globalData.access = access(responseCurrentUser.data);
                    app.globalData.currentUser = responseCurrentUser.data;
                    wx.setStorageSync('currentUser', responseCurrentUser.data);// 存到缓存
                    app.globalData.isLogin = true;
                    const pages = getCurrentPages();
                    const home = "pages/home/index";
                    console.log('getCurrentPages', pages);
                    if (pages[pages.length - 1].route !== home && !silent) {
                        wx.reLaunch({
                            url: '/' + home
                        })
                    }
                    typeof callBack === 'function' && callBack()
                }
            });
        }
    }
}

/**
 * 隐藏分享菜单
 */
export const hideShareMenu = () => {
    wx.hideShareMenu({
        menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
}
/**
 * 重写page
 */
export const newPage = (obj = {}) => {
    let defaultSet = {
        onShow() {
            wx.hideShareMenu({
                menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
            })
        }
    }
    return Page({...defaultSet, ...obj})
}
/**
 * 字体大小计算处理
 */
export const fontSizeCalc = (rpx: number) => {
    let {globalData} = getApp();
    if (globalData.windowWidth >= 480) {// ipad的计算处理
        return rpx * 480 / globalData.windowWidth
    }
    return rpx
}

/**
 * 是否早于当前时间
 */
export const isBeforeNowTime = (time: string) => {
    let boo = true;
    const nowTime = new Date().getTime();
    try {
        const timeS = new Date(time).getTime();
        boo = (nowTime - timeS) >= 0;// 当前时间大于所选时间
    } catch (e) {
        console.log(e);
    }
    boo && wx.showToast({
        title: '所选时间应迟于当前时间',
        icon: "none",
        duration: 1500
    })
    return boo
}

/**
 * 是否超过了当前时间
 */
export const isOverNowTime = (time: string) => {
    let boo = true;
    const nowTime = new Date().getTime();
    try {
        const timeS = new Date(time).getTime();
        boo = (nowTime - timeS) < 0;// 当前时间小于所选时间
    } catch (e) {
        console.log(e);
    }
    boo && wx.showToast({
        title: '所选时间应早于当前时间',
        icon: "none",
        duration: 1500
    })
    return boo
}

/**
 * 静默登录
 */
export const silentLogin = (callBack: Function) =>{
    // 登录过了，这里要做一个判断处理
    wx.showNavigationBarLoading();
    //用户登录过期，重新登录
    wx.login({
        success: res => {
            loginWxampForWechatFun(res.code, true, ()=>{
                callBack && callBack()
            });
        },
        complete: ()=>{
            wx.hideLoading();
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh()
        }
    })
}

/**
 * 获取账号信息
 */
export const getCountInfo = (_that: any) =>{
    let {globalData: {access, currentUser}} = getApp();
    _that.setData({
        access,
        currentUser,
    })
}

/**
 * 判断是否是从微信跳转过来的
 */

export const isWXMP = (options) =>{
    return options?.channel === 'wxmp'
}